package com.redsoil.house.ui.property.fragment;

import android.os.Bundle;
import android.support.annotation.ColorRes;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.redsoil.house.R;
import com.redsoil.house.app.AppContext;
import com.redsoil.house.base.RootFragment;
import com.redsoil.house.model.bean.BarChartBean.StFinDateBean.VtDateValueAvgBean;
import com.redsoil.house.model.bean.BarChartBean.StFinDateBean.VtDateValueBean;
import com.redsoil.house.model.bean.IncomeRoomVO;
import com.redsoil.house.model.bean.OnePropertyVO;
import com.redsoil.house.model.bean.RoomEarnVO;
import com.redsoil.house.ui.property.adapter.PropertyIncomeAdapter;
import com.redsoil.house.ui.property.contract.PropertyIncomeContract;
import com.redsoil.house.ui.property.presenter.PropertyIncomePresenter;
import com.redsoil.house.utils.Util;
import com.redsoil.house.widget.PropertyInfoItem;
import com.zhy.autolayout.AutoLinearLayout;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.addapp.pickers.picker.NumberPicker;

/**
 * 物业信息
 * 收益
 * https://blog.csdn.net/ww897532167/article/details/74171294
 * https://blog.csdn.net/u014614038/article/details/77848593
 */
public class PropertyIncomeFragment extends RootFragment<PropertyIncomePresenter> implements PropertyIncomeContract.View {

    @BindView(R.id.rent)
    PropertyInfoItem rent;

    @BindView(R.id.public_welfare)
    PropertyInfoItem public_welfare;

    @BindView(R.id.repair_cost)
    PropertyInfoItem repair_cost;

    @BindView(R.id.extras)
    PropertyInfoItem extras;

    @BindView(R.id.escrow_charges)
    PropertyInfoItem escrow_charges;

    @BindView(R.id.maintenance_equipment)
    PropertyInfoItem maintenance_equipment;

    @BindView(R.id.taxes)
    PropertyInfoItem taxes;

    @BindView(R.id.service_charge)
    PropertyInfoItem service_charge;

    @BindView(R.id.other_charge)
    PropertyInfoItem other_charge;

    @BindView(R.id.jsr)
    PropertyInfoItem jsr;

//    @BindView(R.id.zzc)
//    PropertyInfoItem zzc;

    @BindView(R.id.other_room_layout)
    AutoLinearLayout other_room_layout;

    //头部信息
    @BindView(R.id.property_income_year_tv)
    TextView property_income_year_tv;

    @BindView(R.id.property_income_rmb_tv)
    TextView property_income_rmb_tv;

    @BindView(R.id.property_income_other_rmb_tv)
    TextView property_income_other_rmb_tv;

    //月信息
    @BindView(R.id.month_info_title_tv)
    TextView month_info_title_tv;

    @BindView(R.id.rmb_tv)
    TextView rmb_tv;

    @BindView(R.id.other_rmb_tv)
    TextView other_rmb_tv;

    @BindView(R.id.chart)
    BarChart chart;

    private RoomEarnVO roomEarnVO;

    private YAxis leftAxis;             //左侧Y轴
    private YAxis rightAxis;            //右侧Y轴
    private XAxis xAxis;                //X轴
    private Legend legend;

    private String propertyId;

    private int currentYear = 2019;

    @BindView(R.id.property_income_layout)
    AutoLinearLayout property_income_layout;

    @BindView(R.id.rv_list)
    RecyclerView rv_list;

    @BindView(R.id.scroll_view)
    ScrollView scroll_view;

    private PropertyIncomeAdapter propertyIncomeAdapter;

    private String roomid;

    private String realtyId;

    private int showIndex = 0;

    public static PropertyIncomeFragment newInstance(String propertyId) {
        Bundle args = new Bundle();

        PropertyIncomeFragment fragment = new PropertyIncomeFragment();
        fragment.setArguments(args);
        args.putString("propertyId",propertyId);
        return fragment;
    }

    @Override
    protected void initEventAndData() {

        super.initEventAndData();

        propertyId = getArguments().getString("propertyId");

        stateLoading();

        initChart();

        mPresenter.getOneProperty(propertyId);
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if(showIndex == 2 && propertyId != null){
            property_income_layout.setVisibility(View.GONE);
            scroll_view.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void getOnePropertySuccess(OnePropertyVO onePropertyVO) {
//        mPresenter.getRoomEarnList("52cbe55e196544fda8b8647bce2af8d9","2019","USD");

        //获取基础信息
        if(onePropertyVO.getRooms()!=null && onePropertyVO.getRooms().size() > 0){
            realtyId = onePropertyVO.getRooms().get(0).getRealtyId();
            mPresenter.getRoomEarnList(roomid,currentYear+"", AppContext.getInstance().getCurrentMoneyType(),realtyId);

//            rv_list.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL));
//            rv_list.setLayoutManager(new LinearLayoutManager(getContext()));
//
//            propertyLeaseAdapter = new PropertyLeaseAdapter(R.layout.property_lease_list_item,onePropertyVO.getRooms());
//
//            propertyLeaseAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//                @Override
//                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                    //只有 租赁中能进入查看
////                    state = 2
//                    OnePropertyVO.RoomsBean data = (OnePropertyVO.RoomsBean) adapter.getData().get(position);
//
//                    if(data.getState().equals("2")){
//                        stateLoading();
//                        roomid = data.getId();
//                        mPresenter.getRoomEarnList(roomid,currentYear+"", AppContext.getInstance().getCurrentMoneyType());
//                    }
//                }
//            });
//
//            rv_list.setAdapter(propertyLeaseAdapter);
//
//            stateMain();

        }else {
            //请求接口
            other_room_layout.setVisibility(View.GONE);
            roomid = onePropertyVO.getRoomId();
            mPresenter.getRoomEarnList(roomid,currentYear+"", AppContext.getInstance().getCurrentMoneyType(),realtyId);
        }

    }

    private void initChart(){
        initBarChart(chart);
    }

    /**
     * @param xValues   X轴的值
     * @param dataLists LinkedHashMap<String, List<Float>>
     *                  key对应柱状图名字  List<Float> 对应每类柱状图的Y值
     * @param colors
     */
    public void showBarChart(final List<String> xValues, LinkedHashMap<String, List<Float>> dataLists,
                             @ColorRes List<Integer> colors) {

        List<IBarDataSet> dataSets = new ArrayList<>();
        int currentPosition = 0;//用于柱状图颜色集合的index

        for (LinkedHashMap.Entry<String, List<Float>> entry : dataLists.entrySet()) {
            String name = entry.getKey();
            List<Float> yValueList = entry.getValue();

            List<BarEntry> entries = new ArrayList<>();

            for (int i = 0; i < yValueList.size(); i++) {
                entries.add(new BarEntry(i, yValueList.get(i)));
//                entries.add(new BarEntry(i, yValueList.get(i), name));
            }
            // 每一个BarDataSet代表一类柱状图
            BarDataSet barDataSet = new BarDataSet(entries, name);
            initBarDataSet(barDataSet, colors.get(currentPosition));
            dataSets.add(barDataSet);

            currentPosition++;
        }

        //X轴自定义值
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return xValues.get((int) value % xValues.size());
            }
        });
        //右侧Y轴自定义值
        rightAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return "";
            }
        });

        BarData data = new BarData(dataSets);
        //*******宽度计算方式就是 BarChart控件宽度 / 柱状图数量  * mBarWidth
        data.setBarWidth(0.5f);
        chart.setData(data);
    }


    /**
     * 柱状图始化设置 一个BarDataSet 代表一列柱状图
     *
     * @param barDataSet 柱状图
     * @param color      柱状图颜色
     */
    private void initBarDataSet(BarDataSet barDataSet, int color) {
        barDataSet.setColor(color);
        barDataSet.setFormLineWidth(1f);
        barDataSet.setFormSize(15.f);
        //不显示柱状图顶部值
        barDataSet.setDrawValues(false);
//        barDataSet.setValueTextSize(10f);
//        barDataSet.setValueTextColor(color);
    }


    /**
     * 初始化BarChart图表
     */
    private void initBarChart(BarChart barChart) {
        /***图表设置***/
        //背景颜色
        barChart.setBackgroundColor(getResources().getColor(R.color.white4ed));
        //不显示图表网格
        barChart.setDrawGridBackground(false);
        //背景阴影
        barChart.setDrawBarShadow(false);
        barChart.setHighlightFullBarEnabled(false);
        //显示边框
        barChart.setDrawBorders(false);
        //设置动画效果
        barChart.animateY(1000, Easing.Linear);
        barChart.animateX(1000, Easing.Linear);

        /***XY轴的设置***/
        //X轴设置显示位置在底部
        xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
//        xAxis.setAxisMinimum(0f);
        xAxis.setGranularity(1f);

        leftAxis = barChart.getAxisLeft();
        rightAxis = barChart.getAxisRight();
        //保证Y轴从0开始，不然会上移一点
//        leftAxis.setAxisMinimum(0f);
//        rightAxis.setAxisMinimum(0f);

        //不显示X轴 Y轴线条
        xAxis.setDrawAxisLine(false);
        leftAxis.setDrawAxisLine(false);
        rightAxis.setDrawAxisLine(false);

        //不显示X轴网格线
        xAxis.setDrawGridLines(false);
        //右侧Y轴网格线设置为虚线
//        rightAxis.enableGridDashedLine(10f, 10f, 0f);
        rightAxis.setDrawGridLines(false);

        //不显示左侧Y轴
        leftAxis.setEnabled(false);

        /***折线图例 标签 设置***/
        legend = barChart.getLegend();
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextSize(11f);
        //显示位置
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //是否绘制在图表里面
        legend.setDrawInside(false);

        barChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
//                e.getX();       //X轴坐标 记得转 int
//                e.getY();       //当前柱状图Y轴值
//                e.getIcon();    //对应 BarEntry(float x, float y, Drawable icon)
//                e.getData();    //对应 BarEntry

                for (IBarDataSet dataSet : chart.getBarData().getDataSets()) {
                    BarEntry entry = dataSet.getEntryForIndex((int) e.getX());
                    entry.getData();
                }
                int postion = Math.round(e.getX());
                if(roomEarnVO.getEveryMonth().size() > postion){
                    changePropertyValue(postion);
                }
            }

            @Override
            public void onNothingSelected() {
            }
        });

    }

    @Override
    public void getRoomEarnListSuccess(RoomEarnVO roomEarnVO) {

        this.roomEarnVO = roomEarnVO;

        property_income_rmb_tv.setText(Util.nfValue(roomEarnVO.getTotalJMoney()));
        property_income_other_rmb_tv.setText("("+AppContext.getInstance().getCurrentMoneyType()+Util.nfValue(roomEarnVO.getTotalMoney())+")");

        List<VtDateValueBean> valueList = new ArrayList<VtDateValueBean>();
        List<VtDateValueAvgBean> avgValueList = new ArrayList<VtDateValueAvgBean>();

//        for (int i=0;i<10;i++){
////            RoomEarnVO.DataListBean bean = (RoomEarnVO.DataListBean)roomEarnVO.getDataList().get(i);
//            VtDateValueBean vtDateValueBean = new VtDateValueBean();
//            vtDateValueBean.setFValue((int)(Math.random()*400+1));
//            vtDateValueBean.setSYearMonth(i+"");
//            valueList.add(vtDateValueBean);
//
//            VtDateValueAvgBean vtDateValueAvgBean = new VtDateValueAvgBean();
//            vtDateValueAvgBean.setFValue((int)(Math.random()*400+1));
//            vtDateValueAvgBean.setSYearMonth(i+"");
//            avgValueList.add(vtDateValueAvgBean);
//
//        }

        //zzc总支出费用  jsr 净收入
        int monthMum = roomEarnVO.getEveryMonth().size();
        for (int i=0;i<Math.max(monthMum,6);i++){
            //编制最少 6 个数据
            VtDateValueBean vtDateValueBean = new VtDateValueBean();

            VtDateValueAvgBean vtDateValueAvgBean = new VtDateValueAvgBean();

            if(monthMum>i){
                RoomEarnVO.EveryMonthBean bean = (RoomEarnVO.EveryMonthBean)roomEarnVO.getEveryMonth().get(i);

                vtDateValueBean.setFValue(bean.getZzc()
                        +Math.abs(bean.getJsr()));
                vtDateValueBean.setSYearMonth(bean.getAccountDate().split("-")[1]);

                vtDateValueAvgBean.setFValue(Math.abs(bean.getJsr()));
                vtDateValueAvgBean.setSYearMonth(bean.getAccountDate());
            }else {
                vtDateValueBean.setFValue(0);
                vtDateValueBean.setSYearMonth("");

                vtDateValueAvgBean.setFValue(0);
                vtDateValueAvgBean.setSYearMonth("");
            }

            valueList.add(vtDateValueBean);

            avgValueList.add(vtDateValueAvgBean);
        }

        //处理数据是 记得判断每条柱状图对应的数据集合 长度是否一致
        LinkedHashMap<String, List<Float>> chartDataMap = new LinkedHashMap<>();
        List<String> xValues = new ArrayList<>();
        List<Float> yValue1 = new ArrayList<>();
        List<Float> yValue2 = new ArrayList<>();
        List<Integer> colors = Arrays.asList(
                getResources().getColor(R.color.orange96c), getResources().getColor(R.color.blue6db)
        );

//        Collections.reverse(valueList);

        for (VtDateValueBean valueBean : valueList) {
            xValues.add(valueBean.getSYearMonth());
            yValue1.add((float) valueBean.getFValue());
        }
        for (VtDateValueAvgBean valueAvgBean : avgValueList) {
            yValue2.add((float) valueAvgBean.getFValue());
        }
        chartDataMap.put("总支出", yValue1);
        chartDataMap.put("净收入", yValue2);

        chart.clear();
        showBarChart(xValues, chartDataMap, colors);

        //去除Description
        chart.setDescription(null);
        chart.setDoubleTapToZoomEnabled(false);//取消双击缩放

//        zzc.setData("总支出","0",getResources().getDrawable(R.drawable.shape_bottom_edge));
        jsr.setData("净收入","0",getResources().getDrawable(R.drawable.shape_bottom_edge));
        rent.setData("总租金","0",getResources().getDrawable(R.drawable.shape_bottom_edge));
        public_welfare.setData(getResources().getString(R.string.public_welfare),"0",getResources().getDrawable(R.drawable.shape_bottom_edge));
        repair_cost.setData(getResources().getString(R.string.repair_cost),"0",getResources().getDrawable(R.drawable.shape_bottom_edge));
        extras.setData(getResources().getString(R.string.extras),"0",getResources().getDrawable(R.drawable.shape_bottom_edge));
        escrow_charges.setData(getResources().getString(R.string.escrow_charges),"0",getResources().getDrawable(R.drawable.shape_bottom_edge));
        maintenance_equipment.setData(getResources().getString(R.string.maintenance_equipment),"0",getResources().getDrawable(R.drawable.shape_bottom_edge));
        taxes.setData(getResources().getString(R.string.taxes),"0",getResources().getDrawable(R.drawable.shape_bottom_edge));
        service_charge.setData(getResources().getString(R.string.service_charge),"0",getResources().getDrawable(R.drawable.shape_bottom_edge));
        other_charge.setData(getResources().getString(R.string.other_charge),"0",getResources().getDrawable(R.drawable.shape_bottom_edge));

        month_info_title_tv.setText("费用详情");

        rmb_tv.setText("");
        other_rmb_tv.setText("");

        if(roomEarnVO.getEveryMonth().size() == 0){
//            stateEmpty();
        }else {
            changePropertyValue(0);
        }

        property_income_layout.setVisibility(View.GONE);
        scroll_view.setVisibility(View.VISIBLE);

        stateMain();

    }

    private void changePropertyValue(int postion){
        RoomEarnVO.EveryMonthBean bean = (RoomEarnVO.EveryMonthBean)roomEarnVO.getEveryMonth().get(postion);

//        zzc.setValue(Util.nfDoubleValue(bean.getJzzc())
//                + "("+AppContext.getInstance().getCurrentMoneyType()
//                +Util.nfDoubleValue(bean.getZzc())+")");

        jsr.setValue(Util.nfValue(bean.getJjsr())
                +"("+AppContext.getInstance().getCurrentMoneyType()
                +Util.nfValue(bean.getJsr())+")");

        rent.setValue(Util.nfValue(bean.getJrent())
                +"("+AppContext.getInstance().getCurrentMoneyType()
                +Util.nfValue(bean.getRent())+")");
        //管理费
        public_welfare.setValue(Util.nfValue(bean.getJmanageCost())
                +"("+AppContext.getInstance().getCurrentMoneyType()
                +Util.nfValue(bean.getManageCost())+")");
        //修缮
        repair_cost.setValue(Util.nfValue(bean.getJfixCost())
                +"("+AppContext.getInstance().getCurrentMoneyType()
                +Util.nfValue(bean.getFixCost())+")");
        //日常杂费
        extras.setValue(Util.nfValue(bean.getJdayCost())
                +"("+AppContext.getInstance().getCurrentMoneyType()
                +Util.nfValue(bean.getDayCost())+")");
        //代管费
        escrow_charges.setValue(Util.nfValue(bean.getJagencyCost())+
                "("+AppContext.getInstance().getCurrentMoneyType()
                +Util.nfValue(bean.getAgencyCost())+")");
        //设备维修费
        maintenance_equipment.setValue(Util.nfValue(bean.getJeqFixCost())+
                "("+AppContext.getInstance().getCurrentMoneyType()
                +Util.nfValue(bean.getEqFixCost())+")");
        //税金
        taxes.setValue(Util.nfValue(bean.getJtaxesCost())
                +"("+AppContext.getInstance().getCurrentMoneyType()
                +Util.nfValue(bean.getTaxesCost())+")");
        //手续费
        service_charge.setValue(Util.nfValue(bean.getJserviceCost())
                +"("+AppContext.getInstance().getCurrentMoneyType()
                +Util.nfValue(bean.getServiceCost())+")");
        //
        other_charge.setValue(Util.nfValue(bean.getJotherCost())
                +"("+AppContext.getInstance().getCurrentMoneyType()
                +Util.nfValue(bean.getOtherCost())+")");

        //
        month_info_title_tv.setText(bean.getAccountDate().split("-")[1]+"月费用详情");

        rmb_tv.setText(Util.nfValue(bean.getJzzc()));
        other_rmb_tv.setText("("+AppContext.getInstance().getCurrentMoneyType()
                +Util.nfValue(bean.getZzc())+")");

        if(bean.getRooms()!=null && bean.getRooms().size() > 0){

            other_room_layout.setVisibility(View.VISIBLE);

            List<IncomeRoomVO> list = new ArrayList<IncomeRoomVO>();

            double allRent = 0;
            double allJrent = 0;

            IncomeRoomVO roomAll = new IncomeRoomVO();
            list.add(roomAll);

            //初始化room数据
            for (int i=0;i<bean.getRooms().size();i++){

                RoomEarnVO.EveryMonthBean.RoomsBean roomsBean = bean.getRooms().get(i);

                IncomeRoomVO roomNumber = new IncomeRoomVO();
                roomNumber.setTitle("房间号");
                roomNumber.setLabel(roomsBean.getRoomNum());

                IncomeRoomVO roomValue = new IncomeRoomVO();
                roomValue.setTitle("租金");
                roomValue.setLabel(Util.nfValue(roomsBean.getJrent())
                        +"("+AppContext.getInstance().getCurrentMoneyType()
                        +Util.nfValue(roomsBean.getRent())+")");

                allRent = allRent + roomsBean.getRent();
                allJrent = allJrent + roomsBean.getJrent();

                list.add(roomNumber);
                list.add(roomValue);
            }


            roomAll.setTitle("各房间总租金");
            roomAll.setLabel(Util.nfValue(allJrent)
                    +"("+AppContext.getInstance().getCurrentMoneyType()
                    +Util.nfValue(allRent)+")");

            if(propertyIncomeAdapter == null){
                rv_list.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL));
                rv_list.setLayoutManager(new LinearLayoutManager(getContext()));

                propertyIncomeAdapter = new PropertyIncomeAdapter(R.layout.property_info_item,list);

                rv_list.setAdapter(propertyIncomeAdapter);
            }



        }else {
            other_room_layout.setVisibility(View.GONE);
        }
    }

    @OnClick(R.id.other_room_layout)
    void otherRoomLayout(){
        property_income_layout.setVisibility(View.VISIBLE);
        scroll_view.setVisibility(View.GONE);
        showIndex = 2;
    }

    @OnClick(R.id.property_income_year_tv)
    void onYearClick(){
        NumberPicker picker = new NumberPicker(getActivity());
        picker.setWidth(picker.getScreenWidthPixels());
        picker.setCanLoop(true);
        picker.setLineVisible(false);
        picker.setWheelModeEnable(true);
        picker.setOffset(2);//偏移量
        picker.setRange(2015, 2025, 1);//数字范围
        picker.setSelectedItem(currentYear);
        picker.setLabel("年");
        picker.setGravity(Gravity.BOTTOM);//居中
        picker.setOnNumberPickListener(new NumberPicker.OnNumberPickListener() {
            @Override
            public void onNumberPicked(int index, Number item) {
                currentYear = item.intValue();
                property_income_year_tv.setText(currentYear+"年");
//                mPresenter.getRoomEarnList("1",currentYear+"",AppContext.getInstance().getCurrentMoneyType());
                mPresenter.getRoomEarnList(roomid,currentYear+"", AppContext.getInstance().getCurrentMoneyType(),realtyId);
            }
        });
        picker.show();
    }

    @Override
    public void responeError(String errorMsg) {
        stateError();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_property_income;
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }
}
